<?php
namespace app\home\model;

use think\Model;

class Message extends Model {
    function add($data = []) {
        $data ['addtime'] = time();
        $data ['addip'] = get_client_ip();
        $this->insert($data);
        return $this->getLastInsID();
    }

    /**
     * 列表
     * @param $param $data
     * @return Array（'list'=>"列表",page=>'当前页面','epage'=>'页数','total_page'=>'总页面'）
     */
    function getList($data = []) {
        $prefix = config('database.prefix');
        $_sql = "where 1=1 ";
        if (isset($data['status']) && $data['status'] != '' || isset($data['status']) && $data['status'] == "0") {
            $_sql .= " and p1.status='{$data['status']}'";
        }

        if (isset($data['time'])) {
            switch ($data['time']) {
                case 1:
                case 3:
                case 6:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  months') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' months ');
                    break;
                case 7:
                    $_sql .= " and p1.addtime <= " . strtotime('+ ' . $data['time'] . '  days') . " and p1.addtime >= " . strtotime('-' . $data['time'] . ' days');
                    break;
            }
        }

        if (isset($data['type'])) {
            $_sql .= empty($data['type']) ? '' : ' and p1.type="' . $data['type'] . '"';
        }
        $receive_result = 1;
        if (isset($data['user_id']) && $data['user_id'] != "" || isset($data['user_id']) && $data['user_id'] == "0") {
            $sql = "select p1.user_id,p1.username,p2.type_id from `{$prefix}users` as p1 left join `{$prefix}users_info` as p2 on p1.user_id=p2.user_id  where p1.user_id ='{$data['user_id']}'";
            $re = db()->query($sql);
            if (!$re) {
                $receive_result = "";
            } else {
                $result = $re[0];
                $receive_result = $result;
                $_sql .= " and p1.user_id!=0 and (p1.user_id='{$result['user_id']}' or (p1.type='all' and  !find_in_set('{$result['user_id']}',receive_yes)) or ( p1.type='users' and  find_in_set('{$result['username']}',receive_value) and  !find_in_set('{$result['user_id']}',receive_yes)) or (p1.type='user_type' and  p1.receive_id='{$result['type_id']}'  and  !find_in_set('{$result['user_id']}',receive_yes)) ";
                $result = db('users_admin')->where(['user_id' => $result['user_id']])->find();
                if ($result) {
                    $_sql .= " or (p1.type='admin_type' and  p1.receive_id='{$result['type_id']}'  and  !find_in_set('{$result['user_id']}',receive_yes))";
                }
                $_sql .= " )";
            }
        }
        if (isset($data['username']) && $data['username'] != "") {
            $sql = "select p1.user_id,p2.type_id from `{$prefix}users` as p1 left join `{$prefix}users_info` as p2 on p1.user_id=p2.user_id  where p1.username ='{$data['username']}'";
            $re = db()->query($sql);
            if (!$re) {
                $receive_result = "";
            } else {
                $result = $re[0];
                $receive_result = $result;
                $_sql .= " and (p1.user_id='{$result['user_id']}' or (p1.type='all' and  !find_in_set('{$result['user_id']}',receive_yes) ";
                if ($data["regtime"] != "") {
                    $_sql .= " and p1.addtime>'{$data['regtime']}' ";
                }
                $_sql .= ") or ( p1.type='users' and  find_in_set('{$data['username']}',receive_value) and  !find_in_set('{$result['user_id']}',receive_yes)) or (p1.type='user_type' and  p1.receive_id='{$result['type_id']}'  and  !find_in_set('{$result['user_id']}',receive_yes)) ";
                $result = db('users_admin')->where(['user_id' => $result['user_id']])->find();
                if ($result) {
                    $_sql .= " or (p1.type='admin_type' and  p1.receive_id='{$result['type_id']}'  and  !find_in_set('{$result['user_id']}',receive_yes))";
                }
                $_sql .= " )";
            }
        }
        if ($receive_result != "") {
            $_select = "p1.*,p2.username as receive_username,p3.username as send_username";
            $_order = " order by p1.addtime desc ";
            $sql = "select SELECT from {$prefix}message_receive as p1 left join `{$prefix}users` as p2 on p1.user_id=p2.user_id left join `{$prefix}users` as p3 on p1.send_userid=p3.user_id SQL ORDER LIMIT";

            //是否显示全部的信息
            if (isset($data['limit'])) {
                $_limit = "";
                if ($data['limit'] != "all") {
                    $_limit = "  limit " . $data['limit'];
                }
                $sql_total = str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql);
                $list = db()->query($sql_total);
                $noread = 0;
                foreach ($list as $key => $value) {
                    if ($value['status'] == 0) {
                        $noread += 1;
                    }
                }
                $list['total'] = count($list);
                $list['noread'] = $noread;
                return $list;
            }

            $data['page'] = !isset($data['page']) ? 1 : $data['page'];
            $data['epage'] = !isset($data['epage']) ? 10 : $data['epage'];

            $_limit = " limit " . ($data['epage'] * ($data['page'] - 1)) . ", {$data['epage']}";
            $list = db()->query(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($_select, $_sql, $_order, $_limit), $sql));
            $user_type_result = model('users_type')->getList();
            foreach ($user_type_result as $key => $value) {
                $_user_type_result[$value['id']] = $value['name'];
            }
            $admin_type_result = model('users_admin_type')->getList();
            foreach ($admin_type_result as $key => $value) {
                $_admin_type_result[$value['id']] = $value['name'];
            }
            $noread = 0;
            foreach ($list as $key => $value) {
                if ($value['type'] != "user") {
                    $list[$key]["send_username"] = "系统";
                    if ($value['type'] == "user_type") {
                        //$list[$key]["receive_username"] = $_user_type_result[$value['receive_id']];
                    } elseif ($value['type'] == "admin_type") {
                        $list[$key]["receive_username"] = $_admin_type_result[$value['receive_id']];
                    } elseif ($value['type'] == "users") {
                        $list[$key]["receive_username"] = $value['receive_value'];
                    } elseif ($value['type'] == "all") {
                        $list[$key]["receive_username"] = "所有用户";
                    }
                }
                if ($value['status'] == 0) {
                    $noread += 1;
                }
                $list[$key]['contents'] = html_entity_decode($value['contents']);
            }
        }
        return $list;
    }
}